package problem.year2022.Month11;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LiangMu
 * @version \$Id: P1125.java, v 0.1, 2022年11月24日 10:25 LiangMu Exp $$
 */
public class P1125 {
    public static void main(String[] args) {
        P1125 p1125 = new P1125();
        int[] nums = new int[]{73, 55, 36, 5, 55, 14, 9, 7, 72, 52};

        int left = 32, right = 69;
        int i = p1125.numSubarrayBoundedMax2(nums, left, right);
        System.out.println(i);
    }

    public int numSubarrayBoundedMax2(int[] nums, int left, int right) {
        int res = 0, last2 = -1, last1 = -1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] >= left && nums[i] <= right) {
                last1 = i;
            } else if (nums[i] > right) {
                last2 = i;
                last1 = -1;
            }
            if (last1 != -1) {
                res += last1 - last2;
            }
        }
        return res;
    }

    public int numSubarrayBoundedMax(int[] nums, int left, int right) {
        List<Integer> subList = new ArrayList<>();
        int res = 0;
        boolean open = false;
        for (int num : nums) {
            if (open) {
                if (num <= right) {
                    subList.add(num);
                } else {
                    res += compute(subList);
                    subList.clear();
                    open = false;
                }
            } else if (num <= right && num >= left) {
                open = true;
                subList.add(num);
            }
        }
        if (subList.size() > 0) {
            res += compute(subList);
        }
        return res;
    }

    public int compute(List<Integer> list) {
        int res = 0;
        for (int i = 0; i < list.size(); i++) {
            res += list.size() - i;
        }
        return res;
    }

}
